package com.fcbox.bypass;

import com.alibaba.fastjson.JSON;
import com.fcbox.bypass.domain.UicUser;
import com.fcbox.bypass.mapper.UicMapper;
import com.fcbox.bypass.mapper.UicXmlMapper;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.File;
import java.util.List;

/**
 * springBoot 入口类
 * Created by 000498 on 2017/5/12.
 */
@SpringBootApplication
@Slf4j
public class Application implements CommandLineRunner{
	@Autowired
	UicMapper uicMapper;

	@Autowired
	UicXmlMapper uicXmlMapper;

	@Autowired
	SqlSessionFactory sqlSessionFactory;

	@Override
	public void run(String... strings) throws Exception {
		// 通过注解的方式执行sql
		Long userId = uicMapper.getUserIdByMobile("15680908680");
		log.info("uicMapper.getUserIdByMobile-> {}", userId);

		// 通过注解的方式获取到对象
		UicUser userByMobile = uicMapper.getUserByMobile("15680908680");
		log.info("uicMapper.getUserByMobile-> {}", JSON.toJSONString(userByMobile));

		//读取文件
		List<String> userIdList = Files.readLines(new File(strings[0]), Charsets.UTF_8);
//		List<List<String>> partition = Lists.partition(userIdList, 1000);//小技巧，如果List太长，可以通过guava的这个方法给他进行拆分
		// 批量执行sql
		log.info("before batch update, province:{}", Joiner.on(",").join(uicMapper.getProvinceListByMobile("15680908680")));
		SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
		UicMapper uicMapperBatch = sqlSession.getMapper(UicMapper.class);
		try {
			for (String userIdStr : userIdList) {
				if (!Strings.isNullOrEmpty(userIdStr)) {
					uicMapperBatch.updateProvence(Long.valueOf(userIdStr.trim()));
				}
			}
			sqlSession.flushStatements();
		} catch (Exception e){
			log.warn("batch update exception.", e);
		} finally {
			sqlSession.close();
		}
		log.info("after batch update, province:{}", Joiner.on(",").join(uicMapper.getProvinceListByMobile("15680908680")));

		// 通过xml的方式执行sql
		Long userIdByPhone = uicXmlMapper.getUserIdByPhone("15680908680");
		log.info("uicXmlMapper.getUserIdByPhone-> {}", userIdByPhone);
	}

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
